package com.store.framework.rest;

import java.util.List;
import java.util.UUID;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.store.framework.entry.AppAdmin;
import com.store.framework.logic.IAppAdminLogic;
import com.store.framework.logic.imp.AppAdminLogic;

@Path("AdminService")
public class AdminService {
	private static Log LOG = LogFactory.getLog(AdminService.class);

	IAppAdminLogic appadminlogic = new AppAdminLogic();

	@POST
	@Path("addAdmin")
	@Produces("application/json; charset=UTF-8")
	public String AddAdmin(String input) {
		LOG.info(input);
		JSONObject jo = JSONObject.fromObject(input);
		@SuppressWarnings("static-access")
		AppAdmin admin = (AppAdmin) jo.toBean(jo, AppAdmin.class);
		String key = UUID.randomUUID().toString();
		admin.setId(key);
		int row = appadminlogic.Add(admin);
		String mess = "";
		if(row==1){
			 mess = "{\"success\":true,\"id\":\""+key+"\"}";
		}else{
			mess = "{\"success\":false}";
		}
		return mess;
	}

	@POST
	@Path("selectAppAdmin")
	@Produces("application/json; charset=UTF-8")
	public String selectAppAdmin(@FormParam("start") Long start,
			@FormParam("limit") Long limit) {
		List<?> list = appadminlogic.select(start, limit);
		int count = appadminlogic.getCount();
		JSONArray ja = JSONArray.fromObject(list);
		System.out.println(ja);

		return "{\"totalProperty\":" + count + ",\"root\":" + ja.toString()
				+ "}";
	}

	
	@POST
	@Path("deleteAdmin")
	@Produces("application/json; charset=UTF-8")
	public String deleteAdmin(String input) {
		LOG.info(input);
		AppAdmin admin = new AppAdmin();
		admin.setId(input);
		appadminlogic.delete(admin);
		return "{\"result\":1}";
	}

	
	@POST
	@Path("updateAdmin")
	@Produces("application/json; charset=UTF-8")
	public String updateAdmin(String input) {
		LOG.info(input);
		JSONObject jo = JSONObject.fromObject(input);
		@SuppressWarnings("static-access")
		AppAdmin admin = (AppAdmin) jo.toBean(jo, AppAdmin.class);
		int row = 0;
		String msg = "";
		try {
			row = appadminlogic.update(admin);
			if(row == 1){
				msg = "{\"success\":true}";
			}
		} catch (Exception e) {
			msg = "{\"success\":false,errorMsg:\""+e.getMessage()+"\"}";
		}
		return msg;
	}

	
	public static void main(String[] args) {
		// new AdminService().selectAppAdmin();
	}
}
